using MediatR;
using SmartTracking.ErrorCode;
using SmartTracking.Domain.EWE;
using SmartTracking.Infrastructure.Interfaces;
using AutoMapper;
using Yitter.IdGenerator;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Threading;
using static System.Runtime.InteropServices.JavaScript.JSType;
using System;
using System.Transactions;

namespace SmartTracking.ApiWrite.Applications.Commands.Ewemating
{
    /// <summary>
    /// 批量添加母羊配种处理器
    /// </summary>
    public class AddBatchEwematingCommandHandler : IRequestHandler<AddBatchEwematingCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<Ewematings> eRep;
        private readonly IBaseRepository<MainMating> mRep;
        private readonly IMapper mapper;

        public AddBatchEwematingCommandHandler(IBaseRepository<Ewematings> eRep, IMapper mapper, IBaseRepository<MainMating> mRep)
        {
            this.eRep = eRep;
            this.mapper = mapper;
            this.mRep = mRep;
        }

        public async Task<ApiResult<int>> Handle(AddBatchEwematingCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> result = new ApiResult<int>();
            
            if (request.EwematingList == null || request.EwematingList.Count == 0)
            {
                result.Code = ApiEnum.新增失败;
                result.Message = "参数错误，配种数据列表不能为空";
                return result;
            }
            
            try
            {
                List<Ewematings> ewematingsList = new List<Ewematings>();
                
                MainMating ma = new MainMating();
                ma.ResponsibleFor = request.ResponsibleFor;
                ma.MainMatingTime = request.MainMatingTime;
                // 自动生成单据编号：日期时间(年月日时分秒) + 雪花ID
                string timestamp = DateTime.Now.ToString("yyyyMMddHHmmss");
                long snowflakeId = YitIdHelper.NextId();
                ma.DocumentNumber = $"{timestamp}{snowflakeId}";
                ma.SerialNumber = $"{timestamp}{snowflakeId}";
                await mRep.AddAsync(ma);
                foreach (var item in request.EwematingList)
                {
                    Ewematings ewemating = mapper.Map<Ewematings>(item);
                    //ewemating.EwematingSnowId = YitIdHelper.NextId().ToString();
                    ewemating.EwematingTime=DateTime.Now;   
                    ewemating.IsDeleted = false;
                    ewematingsList.Add(ewemating);
                }

                int affectedRows = await eRep.AddRangeAsync(ewematingsList);
                
                if (affectedRows > 0)
                {
                    result.Code = ApiEnum.新增成功;
                    result.Message = $"批量添加成功，共添加{affectedRows}条记录";
                    result.data = affectedRows;
                }
                else
                {
                    result.Code = ApiEnum.新增失败;
                    result.Message = "批量添加失败";
                }
            }
            catch (System.Exception ex)
            {
                result.Code = ApiEnum.新增失败;
                result.Message = "批量添加过程中发生错误：" + ex.Message;
            }

            return result;
        }
    }
}